#include <mqueue.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <iostream>
using namespace std;

#define FILE_MODE S_IRUSR|S_IWUSR

struct mq_attr attr;

int main(int argc, char** argv){
    int c, flags;
    mqd_t mqd;
    flags = O_RDWR|O_CREAT;
    
    while( ( c = getopt(argc, argv, "em:z:" ) ) != -1 ){
        switch (c){
        case 'e':
            flags |= O_EXCL;
            cout << "e is specified!" << endl;
            break;
        case 'm':
            attr.mq_maxmsg = atol(optarg);
            cout << "m is specified: " << attr.mq_maxmsg << endl;
            break;
        case 'z':
            attr.mq_msgsize = atol(optarg);
            cout << "z is spcified: " << attr.mq_msgsize <<endl;
            break;
        }
    }
    printf("optind = %d\n", optind);
    
    if( optind != argc - 1 ){
        printf("usage: mqcreate [ -e ]  [-m maxmsg -z msgsize] <name>\n");
        return  -1;
    }



    if(( attr.mq_maxmsg != 0 && attr.mq_msgsize == 0 ) ||
       (attr.mq_maxmsg == 0 && attr.mq_msgsize != 0)){
        printf("must specify bothe -m and -z\n");
    }
    


    printf("name = %s\n", argv[optind]);

    struct mq_attr* pattr = NULL;
    if(attr.mq_maxmsg != 0){
        pattr = &attr;
    }
    
    //mqd = mq_open( argv[optind], flags, FILE_MODE, pattr);
    mqd = mq_open( argv[optind], flags, FILE_MODE, NULL);

    printf("The message queue d: %d \n", mqd);
    if(mqd < 0){
        printf("%d :%s \n", errno, strerror(errno));
        return -1;
    }
    
    mq_close(mqd);
    exit(0);
}
    


